package server;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.IOException;
import java.util.ArrayList;


/**
 * @author Donovan
 * 
 * Server thread runs until program is closed and accepts incoming connections
 *
 */
public class Server extends Thread {

	private static final int PORT = 63400;
	private static final int SLEEP_TIME = 200;
	private ServerSocket serverSocket;
	private InetAddress hostAddress;
	private Socket socket;
	private ArrayList<ClientUser> users = new ArrayList<ClientUser>();
	
	public Server(){
		try {
			hostAddress = InetAddress.getLocalHost();
		} catch(UnknownHostException e) {
			System.out.println("Could not get the host address.");
			return;
		}
		
		System.out.println("Server host address is: " + hostAddress);
		
		try {
			serverSocket = new ServerSocket(PORT, 0, hostAddress);
		} catch(IOException e) {
			System.out.println("Could not open server socket.");
			return;
		}
		
		System.out.println("Socket " + serverSocket + " created");
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Thread#run()
	 * 
	 * Run when called. Will continue executing until program is closed.
	 */
	public void run() {
		
		System.out.println("Server has been started");
		
		while(true){
			for(int i =0; i < users.size(); i++) {
				if(!users.get(i).isConnected()){
					System.out.println(users.get(i) + " removed due to lack of connection.");
					users.remove(i);
				}
			}
			
			try{
				socket = serverSocket.accept();
			} catch(IOException e) {
				System.out.println("Could not connect to a client");
			}
			
			//client has connected
			System.out.println("Client " + socket + " has connected");
			
			users.add(new ClientUser(socket));
			
			//sleep
			try{
				Thread.sleep(SLEEP_TIME);
			} catch(InterruptedException e) {
				System.out.println("Room has been interrupted.");
			}
		}
	}
}
